//
//  HomeCollectionViewController.swift
//  ImageBrowse
//
//  Created by zs on 16/6/18.
//  Copyright © 2016年 zs. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class HomeCollectionViewController: UICollectionViewController {
     lazy var shops : [Shop]  = [Shop]()
    private lazy var photoBrowserAnimator : PhotoBrowserAnimator = PhotoBrowserAnimator()
    override func viewDidLoad() {
        super.viewDidLoad()
      
     
      loadData(0)
    }



    // MARK: UICollectionViewDataSource


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return shops.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! HomeVIewCell
    
        cell.shop = shops[indexPath.item]
       
        //判断是不是最后一个cell出现?
        if indexPath.item == shops.count - 1 {
          
             loadData(shops.count)
        }
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let photobrowserVC = PhotoBrowserController()
        
        // MARK:- 给显示大图的VC 传值
        photobrowserVC.shops = shops
        photobrowserVC.indexPath = indexPath
        
        // MARK:- 设置弹出样式
//        photobrowserVC.modalTransitionStyle = .FlipHorizontal
        
        photobrowserVC.modalPresentationStyle = .Custom
        photobrowserVC.transitioningDelegate = photoBrowserAnimator
        
        presentViewController(photobrowserVC, animated: true, completion: nil)
        
    }

}


// MARK:- 请求数据

extension HomeCollectionViewController {

    private func loadData(offset : Int){
       
        NetworkTools.shareIntance.loadHomeData(offset) { (result) in
            //1.获取结果的字典
            let resultDict = result as! [String : NSObject]
            
            
            //2.根据data key 获取数组
           guard let resultArray = resultDict["data"] as? [[String : NSObject]] else {
               
                print("转成数组错误")
               return
            }
            //3.遍历数组,获取字典,并将字典转换层模型对象
            for dict in resultArray{
            
              let shop = Shop(dict: dict)
                self.shops.append(shop)
            }
            self.collectionView?.reloadData()
        }
    
    }
}









